from history import Ara
from history import Berichten
from history import Zeit
from history import Person

from history import wikidown
from history import HISTORY_DB, Cache
import re

from bs4 import BeautifulSoup


def parse_jareszahl():
    b = wikidown('宋朝')
    jahreszahl = [i for i in b.select('table')[3].select('tr') if len(i) > 3][1:]
    for j in jahreszahl:
        jahre(j)

def jahre(one):
    db = Cache(HISTORY_DB)
    td_start = ''
    td_end = ''
    
    alias = ''
    

    j_alias = one.select('td')[-1].text.split('年')

    
    people_aliases = [one.select('td')[0].text]
    people_aliases += re.sub(r'<.+?>', ' ', one.select('td')[1].decode()).split()
    people_name = one.select('td')[2].text.strip()
    peoples = []

    print('--- parse king ---- : ', people_name)
    for people_alias in people_aliases:
        if db.query_one(Person,name=people_name, alias=people_alias):continue
        
        peoples.append(Person(name=people_name, alias=people_alias))
    db.save_all(*peoples)
    king = people_name

    print('--- generate age ----')
    jahren = []
    for no, j in enumerate(j_alias):
        if not j.strip():continue
        if len(j.split()) > 1:
            alias,td_start = j.split()
        else:
            td_end = j[1:]

        if alias and td_end and td_start:
            for t in range(int(td_start), int(td_end)):
                if db.query_one(Zeit, simple_time=t, alias=alias):continue
                print('       ',t, alias, king)
                z = Zeit(simple_time=t, pro_time=str(t) + "年", alias=alias, king=king)
                jahren.append(z)
                td_start = ''
                td_end = ''


    db.save_all(*jahren)
    return {'king':peoples, 'age':jahren}
